<template>
  <view class="search-page">
    <u-navbar
      title="搜索岗位"
      :border="false"
      bgColor="#FFFFFF"
      titleColor="#333333"
      :titleStyle="{ fontSize: '34rpx', fontWeight: '500' }"
      :placeholder="true"
      :autoBack="true"
    />

    <!-- 顶部搜索栏 -->
    <view class="search-bar">
      <view class="search-row">
        <view class="search-input">
          <u-input
            v-model="keyword"
            placeholder="搜索企业/岗位关键词"
            type="text"
            shape="circle"
            bgColor="#F5F5F5"
            prefixIcon="search"
            :prefixIconStyle="{ color: '#999999' }"
            clearable
            confirmType="search"
            @confirm="onSearch"
            :customStyle="{ width: '100%', height: '56rpx', padding: '0 6rpx' }"
          />
        </view>
        <text class="search-action" @click="onSearch">搜索</text>
      </view>
    </view>

    <!-- 结果列表 -->
    <u-list
      class="result-list"
      :loading="loading"
      :finished="finished"
      @load="loadMore"
	  @scrolltolower="loadMore"
      :immediate-check="false"
      :enable-back-to-top="false"
      :lower-threshold="50"
    >
      <u-list-item v-for="(job, index) in results" :key="index">
        <JobCard
          :job="job"
          :avatarList="job.avatars"
          buttonText="一键报名"
          @cardClick="viewJob"
          @applyClick="applyJob"
        />
      </u-list-item>

      <u-list-item v-if="!loading && results.length === 0">
        <view class="empty-box">
          <u-icon name="search" size="60" color="#CCCCCC" />
          <text class="empty-text">输入关键词试试</text>
        </view>
      </u-list-item>
    </u-list>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import JobCard from '@/components/JobCard.vue'
import { jobApi } from '@/api/api-helper.js'
import { userStore } from '@/stores/userStore'

const keyword = ref('')
const results = ref<any[]>([])
const loading = ref(false)
const finished = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const hasSearched = ref(false)

async function fetchList(isLoadMore = false) {
  if (!hasSearched.value) return
  if (loading.value) return
  try {
    loading.value = true
    const openId = userStore.getOpenId()
    const res = await jobApi.getListToApp({
      currentPage: isLoadMore ? currentPage.value + 1 : 1,
      pageSize: pageSize.value,
      type: 'progress',
      order: 'signUpPersons',
      eosKeyword: keyword.value.trim(),
      openId
    })
    if (res && res.code === 200) {
      const list = (res.data && res.data.list) || []
              const mapped = list.map((job: any) => ({
          id: job.hireRecruitUseId,
          hireRecruitUseId: job.hireRecruitUseId,
          hireRecruitUseEntryId: job.hireRecruitUseEntryId,
          date: formatDate(job.hireStartDate),
          title: job.hireName || '招聘岗位',
          useWorkType: job.useWorkType || '正式工',
          salary: job.workPrice ? `${job.workPrice}` : '面议',
          location: formatLocation(job.customerName, job.address),
          address: job.address,
          customerName: job.customerName,
          distance: job.distance, // 添加距离字段
          signup: job.isSignup, // 是否已报名
          positionName: job.positionName, // 还招岗位
          tags: parseTags(job.enterpriseLabel),
          avatars: job.pictureList || [],
          engagement: formatEngagement(job.followerCount),
          rawData: job
        }))
      if (isLoadMore) {
        results.value.push(...mapped)
        currentPage.value += 1
      } else {
        results.value = mapped
        currentPage.value = 1
      }
      const pg = (res.data && res.data.pagination) || {}
      const total = pg.total || 0
      const sz = pg.pageSize || pageSize.value
      const cp = pg.currentPage || currentPage.value
      finished.value = cp * sz >= total
    }
  } catch (e) {
    finished.value = true
  } finally {
    loading.value = false
  }
}

function onSearch() {
  hasSearched.value = true
  finished.value = false
  currentPage.value = 1
  fetchList(false)
}

function loadMore() {
  if (!hasSearched.value || finished.value) return
  fetchList(true)
}

function viewJob(job: any) {
  uni.navigateTo({ url: `/pages/job-details/job-details?jobId=${job.hireRecruitUseId || job.id}` })
}

function applyJob(job: any) {
  const params = {
    jobId: job.hireRecruitUseId || job.id,
    hireRecruitUseId: job.hireRecruitUseId || job.id,
    hireRecruitUseEntryId: job.hireRecruitUseEntryId || '',
    jobTitle: job.title,
    jobSalary: job.salary,
    jobLocation: job.location,
    customerName: job.customerName,
    useWorkType: job.useWorkType,
    address: job.address,
    jobData: encodeURIComponent(JSON.stringify(job.rawData || job))
  }
  uni.navigateTo({ url: `/pages/job-application/job-application?${Object.entries(params).map(([k, v]) => `${k}=${encodeURIComponent(v as any)}`).join('&')}` })
}

// 工具函數（與首頁一致）
const formatDate = (dateStr: string) => {
  if (!dateStr) return '今日'
  try {
    const date = new Date(dateStr)
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    return `${month}月${day}日`
  } catch {
    return '今日'
  }
}

const formatLocation = (customerName: string, address: any) => {
  if (!customerName && !address) return '未知地点'
  let location = customerName || ''
  if (address) {
    if (typeof address === 'string') {
      location = location ? `${location} ${address}` : address
    } else if (address.province || address.city) {
      if (address.province && address.city) {
        location += `${location ? ' ' : ''}${address.province}-${address.city}`
      } else if (address.province) {
        location += `${location ? ' ' : ''}${address.province}`
      } else if (address.city) {
        location += `${location ? ' ' : ''}${address.city}`
      }
    }
  }
  return location
}

function parseTags(enterpriseLabel: string) {
  if (!enterpriseLabel) return []
  try {
    let tags: any[] = []
    if (enterpriseLabel.startsWith('[')) tags = JSON.parse(enterpriseLabel)
    else tags = enterpriseLabel.split(',').map(t => t.trim())
    return tags.map(t => ({ name: t }))
  } catch { return [] }
}

function formatEngagement(followerCount: number) {
  if (!followerCount) return '暂无关注'
  if (followerCount >= 100) return `已关注 ${Math.floor(followerCount / 100) * 100}+`
  return `已关注 ${followerCount}+`
}
</script>

<style lang="scss" scoped>
.search-page { min-height: 100vh; background-color: #F5F5F5; }
.search-bar { padding: 16rpx 20rpx; background-color: #FFFFFF; }
.search-row { display: flex; align-items: center; }
.search-btn { flex-shrink: 0; }
.result-list { padding: 12rpx; }
.empty-box { padding: 120rpx 0; display: flex; flex-direction: column; align-items: center; }
.empty-text { margin-top: 12rpx; color: #999; font-size: 26rpx; }
.search-input { flex: 1; }
.search-action { margin-left: 42rpx; color: var(--u-primary); font-size: 28rpx; flex-shrink: 0; }
</style>

